package org.skatiger.jrove.spring.tags;

import java.text.MessageFormat;

import org.skatiger.jrove.ExternalContext;
import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.spring.utils.SpringUrlUtil;
import org.skatiger.jrove.spring.utils.SpringUrlUtil.UrlType;
import org.springframework.web.util.HtmlUtils;

public class SpringFunctions {
    private SpringFunctions() {
    }

    public static String simpleUrlEscape(String pattern, Object... args) {
        String urlStr = simpleUrl(pattern, args);
        return HtmlUtils.htmlEscape(urlStr);
    }

    public static String simpleUrl(String pattern, Object... args) {
        UrlType type = SpringUrlUtil.resolveUrlType(pattern);
        StringBuilder url = new StringBuilder();
        ViewContext context = ViewContext.getCurrentInstance();
        ExternalContext extctx = context.getExternalContext();
        if (type == UrlType.CONTEXT_RELATIVE) {
            // add application context to url
            url.append(extctx.getRequestContextPath());
        }
        if (type != UrlType.RELATIVE && type != UrlType.ABSOLUTE
                && !pattern.startsWith("/")) {
            url.append("/");
        }
        url.append(MessageFormat.format(pattern, args));
        String urlStr = url.toString();
        if (type != UrlType.ABSOLUTE) {
            // Add the session identifier if needed
            // (Do not embed the session identifier in a remote link!)
            urlStr = extctx.encodeURL(urlStr);
        }
        return urlStr;
    }
}
